package com.ntt.benew.dictionary.utils

import com.ntt.benew.dictionary.api.XFApiManger
import com.ntt.benew.dictionary.constants.LangType
import com.ntt.benew.dictionary.listener.ITranslateListener
import com.ntt.core.nlogger.NLogger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.lang.Exception

/**
 * Created by Android Studio.
 * User: tw
 * Date: 2023/11/1
 * Time: 11:42
 */
object XFUtils {

    /**
     * 翻译句子
     */
    fun queryTranslate(sentences: String, lang: String, callback: ITranslateListener?) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val xfResult =
                    XFApiManger.getInstance().doTransRequest(sentences, lang, getXFLangTo(lang))
                NLogger.d("queryTranslate -> : $xfResult")
                launch(Dispatchers.Main) {
                    xfResult?.takeIf { it.code == 0 }?.data?.result?.trans_result?.run {
                        callback?.refreshContentView(this.dst, this.src)
                    } ?: kotlin.run {
                        callback?.showErrorView()
                    }
                }
//                ThreadUtils.runOnUiThread {
//                    xfResult?.takeIf { it.code == 0 }?.data?.result?.trans_result?.run {
//                        if (view != null && !view.isFinishing) {
//                            view.showSuccessView()
//                            view.refreshContentView(this.dst, sentences)
//                        }
//                    } ?: kotlin.run {
//                        if (view != null && !view.isFinishing) {
//                            view.showErrorView()
//                        }
//                    }
//                }
            } catch (e: Exception) {
                launch(Dispatchers.Main) {
                    callback?.showErrorView()
                }
//                ThreadUtils.runOnUiThread {
//                    if (view != null && !view.isFinishing) {
//                        view.showErrorView()
//                    }
//                }
            }
        }
    }

    private fun getXFLangTo(lang: String): String {
        return if (lang == LangType.CN) {
            XFApiManger.XF_EN
        } else {
            XFApiManger.XF_CN
        }
    }
}